package pong.game.open_gl;

import java.util.HashMap;
import java.util.Iterator;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;
import android.opengl.GLUtils;
import android.util.Log;

public class TextureMemoryController {

	private static final String TAG = "TextureMemoryController";
	// OpenGL texture ID, Count hrefs, Resource ID
	private final HashMap<Integer, TextureOpenGL> textures = new HashMap<Integer, TextureOpenGL>();

	public void clear() {
		Iterator<Integer> iterator = textures.keySet().iterator();
		while (iterator.hasNext()) {

			TextureOpenGL texture = textures.get(iterator.next());

			texture.minusCounter();

			if (!texture.isUsed())
				clear(texture.getOpenGLId());
		}

		textures.clear();
	}

	private void clear(int openGLId) {
		int[] buffer = { openGLId };
		GLES20.glDeleteTextures(1, buffer, 0);
	}

	public int createOpenGLTexture(Context context, int resourceId, boolean fastTexture) {

		Log.i(TAG, "createOpenGLTexture");
		TextureOpenGL texture = textures.get(resourceId);

		if (texture != null) {
			texture.addCounter();
			return texture.getOpenGLId();
		} else {

			int[] textureId = new int[1];
			GLES20.glGenTextures(1, textureId, 0);

			if (textureId[0] != 0) {
				texture = new TextureOpenGL();
				// textures.put(resourceId, texture);
				texture.addCounter();

				final BitmapFactory.Options options = new BitmapFactory.Options();
				options.inScaled = false; // No pre-scaling

				// Read in the resource
				final Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId, options);

				// int w = bitmap.getWidth();
				// if ((w & (w - 1)) != 0)
				// bitmap = GL_Helper.cropBitmap(bitmap);

				texture.setFastTexture(fastTexture);
				texture.setResourceId(resourceId);
				GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId[0]);

				GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER,
						GLES20.GL_LINEAR_MIPMAP_LINEAR);
				GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
				// GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D,
				// GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_REPEAT);
				// GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D,
				// GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_REPEAT);

				GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
				if (fastTexture) {

				} else {

				}

				GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER,
						GLES20.GL_LINEAR_MIPMAP_LINEAR);
				GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);

				// GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D);

				texture.setOpenGLId(textureId[0]);
				bitmap.recycle();
			} else
				throw new RuntimeException("Error loading texture.");

			return texture.getOpenGLId();
		}
	}

}
